/**
 * 将时间格式化为“刚刚”、“X分钟前”、“昨天”、“MM-DD”或“YYYY-MM-DD”
 * @param {string | number} time - 时间戳（秒或毫秒）或 ISO 字符串
 * @returns {string}
 */
export function formatTimeAgo(time) {
  if (!time) return ''

  // 统一转为毫秒时间戳
  let timestamp
  if (typeof time === 'string') {
    timestamp = new Date(time).getTime()
  } else if (typeof time === 'number') {
    timestamp = time > 1e10 ? time : time * 1000
  } else {
    return ''
  }

  const now = Date.now()
  const diffMs = now - timestamp

  // ✅ 关键修改：未来时间视为“刚刚”
  if (diffMs < 0) {
    return '刚刚'
  }

  const seconds = Math.floor(diffMs / 1000)
  const minutes = Math.floor(seconds / 60)
  const hours = Math.floor(minutes / 60)
  const days = Math.floor(hours / 24)

  if (minutes < 1) return '刚刚'
  if (hours < 1) return `${minutes}分钟前`
  if (days < 1) return `${hours}小时前`

  const today = new Date()
  const targetDate = new Date(timestamp)

  const resetTime = (d) => new Date(d.getFullYear(), d.getMonth(), d.getDate())
  const todayStart = resetTime(today)
  const targetStart = resetTime(targetDate)

  const dayDiff = Math.floor((todayStart - targetStart) / (1000 * 60 * 60 * 24))

  if (dayDiff === 1) return '昨天'
  if (dayDiff === 2) return '前天'

  const threeMonthsAgo = new Date()
  threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3)

  if (timestamp >= threeMonthsAgo.getTime()) {
    const month = String(targetDate.getMonth() + 1).padStart(2, '0')
    const day = String(targetDate.getDate()).padStart(2, '0')
    return `${month}-${day}`
  }

  const year = targetDate.getFullYear()
  const month = String(targetDate.getMonth() + 1).padStart(2, '0')
  const day = String(targetDate.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}